package com.baitiaojun.video.aspect;

import com.baitiaojun.api.annotation.UserAuthoritiesAccess;
import com.baitiaojun.api.exception.ConditionException;
import com.baitiaojun.api.vo.JsonRes;
import com.baitiaojun.video.feign.UserAuthoritiesFeign;
import com.baitiaojun.video.support.UserSupport;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @类名 UserAuthoritiesAspect
 * @描述 TODO 数据权限校验
 * @作者 白条君
 * @创建日期 2022/12/7 23:49
 * @版本 1.0
 */
@Order(1)
@Component
@Aspect
public class UserAuthoritiesAspect {

    @Resource
    private UserSupport userSupport;

    @Resource
    private HttpServletRequest request;

    @Resource
    private UserAuthoritiesFeign userAuthoritiesFeign;

    @Pointcut("@annotation(com.baitiaojun.api.annotation.UserAuthoritiesAccess)")
    public void pointCut() {}

    //接口权限
    @Before(value = "@annotation(userAuthoritiesAccess) && pointCut()")
    public void before(UserAuthoritiesAccess userAuthoritiesAccess) throws Exception {
        String[] userAuthorities = userAuthoritiesAccess.accessRole();
        Set<String> userAuthoritiesSet = Arrays.stream(userAuthorities).collect(Collectors.toSet());
        Long userId = userSupport.getCurrentUserId(request);
        JsonRes jsonRes = userAuthoritiesFeign.getRoleCode(userId);
        if ((int) jsonRes.success().get("status") == 1) {
            String roleCode = (String) jsonRes.get("data");
            /**
             * 如果AB中有相同的元素，那么A中会保留相同的元素，将不同的元素移除
             * 如果AB中没有相同的元素，那么会返回[]
             * 当A中的元素有变化时会返回true，没有变化会返回false
             */
            userAuthoritiesSet.retainAll(Collections.singleton(roleCode));
            if (userAuthoritiesSet.size() == 0) {
                throw new ConditionException("用户权限不足");
            }
        }
    }

    //数据权限
}
